package ltd.nullpointer.tcp.core.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

/*
 * AES对称加密和解密
 */
public class AesUtil {

	/**
	 * aes+base64加密
	 * 
	 * @param key
	 * @param content
	 * @return
	 */
	public static String aesEncodeWithBase64(String key, String content) {
		String str = aesEncode(key, content);
		str = Base64Util.getBase64(str);
		return str;
	}

	/**
	 * aes+base64解密
	 * 
	 * @param key
	 * @param content
	 * @return
	 */
	public static String aesDecodeWithBase64(String key, String content) {
		String str = Base64Util.getFromBase64(content);
		str = aesDecode(key, str);
		return str;
	}

	/*
	 * 加密 1.构造密钥生成器 2.根据ecnodeRules规则初始化密钥生成器 3.产生密钥 4.创建和初始化密码器 5.内容加密 6.返回字符串
	 */
	public static String aesEncode(String key, String content) {
		try {
			byte[] aesByte = aesEncode(key, content.getBytes("UTF-8"));
			// 10.将加密后的数据转换为字符串
			// 这里用Base64Encoder中会找不到包
			// 解决办法：
			// 在项目的Build path中先移除JRE System Library，再添加库JRE System Library，重新编译后就一切正常了。
			String aesEncode = new String(new BASE64Encoder().encode(aesByte));
			// 11.将字符串返回
			return aesEncode;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 如果有错就返加nulll
		return null;
	}

	public static byte[] aesEncode(String key, byte[] content) throws NoSuchAlgorithmException, NoSuchPaddingException,
			InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException {
		// 1.构造密钥生成器，指定为AES算法,不区分大小写
		KeyGenerator keygen = KeyGenerator.getInstance("AES");
		// 2.根据ecnodeRules规则初始化密钥生成器
		// 生成一个128位的随机源,根据传入的字节数组
		// keygen.regHeader(128, new SecureRandom(encodeRules.getBytes()));

		// 兼容linux
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(key.getBytes());
		keygen.init(128, random);

		// 3.产生原始对称密钥
		SecretKey originalKey = keygen.generateKey();
		// 4.获得原始对称密钥的字节数组
		byte[] raw = originalKey.getEncoded();
		// 5.根据字节数组生成AES密钥
		SecretKey keySpec = new SecretKeySpec(raw, "AES");
		// 6.根据指定算法AES自成密码器
		Cipher cipher = Cipher.getInstance("AES");
		// 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作，第二个参数为使用的KEY
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
		// 9.根据密码器的初始化方式--加密：将数据加密
		byte[] aesByte = cipher.doFinal(content);
		return aesByte;
	}

	/*
	 * 解密 解密过程： 1.同加密1-4步 2.将加密后的字符串反纺成byte[]数组 3.将加密内容解密
	 */
	public static String aesDecode(String key, String content) {
		try {
			byte[] contentByte = new BASE64Decoder().decodeBuffer(content);
			byte[] decodeByte = aesDecode(key, contentByte);
			String aesDecode = new String(decodeByte, "utf-8");
			return aesDecode;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		// 如果有错就返加nulll
		return null;
	}

	public static byte[] aesDecode(String key, byte[] contentByte) throws NoSuchAlgorithmException,
			NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		// 1.构造密钥生成器，指定为AES算法,不区分大小写
		KeyGenerator keygen = KeyGenerator.getInstance("AES");
		// 2.根据ecnodeRules规则初始化密钥生成器
		// 生成一个128位的随机源,根据传入的字节数组
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(key.getBytes());
		keygen.init(128, random);

		// keygen.regHeader(128, new SecureRandom(key.getBytes()));
		// 3.产生原始对称密钥
		SecretKey originalKey = keygen.generateKey();
		// 4.获得原始对称密钥的字节数组
		byte[] raw = originalKey.getEncoded();
		// 5.根据字节数组生成AES密钥
		SecretKey key0 = new SecretKeySpec(raw, "AES");
		// 6.根据指定算法AES自成密码器
		Cipher cipher = Cipher.getInstance("AES");
		// 7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
		cipher.init(Cipher.DECRYPT_MODE, key0);
		// 8.将加密并编码后的内容解码成字节数组
		/*
		 * 解密
		 */
		byte[] decodeByte = cipher.doFinal(contentByte);
		return decodeByte;
	}

	public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
			IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		String encodeRules = "zhangweilin_productType_boot2_ark_iot_2017-12-22 17:36:52";
		String content = "12";
		/*
		 * 加密
		 */
		String str = aesEncode(encodeRules, content);
		System.out.println("根据输入的规则" + encodeRules + "加密后的密文是:" + str);

		/*
		 * 解密
		 */
		String str2 = aesDecode(encodeRules, str);
		System.out.println("根据输入的规则" + encodeRules + "解密后的明文是:" + str2);

		System.out.println("以下为经过base64包装的");

		String str3 = aesEncode(encodeRules, content);
		System.out.println("str3: " + str3);
		String str4 = Base64Util.getBase64(str3);
		System.out.println("str4: " + str4);

		str4 = "YWdOU1o1YUxDdmwyQzNtWU83eDNYdz09";
		String str5 = Base64Util.getFromBase64(str4);
		System.out.println("str5: " + str5);
		String str6 = aesDecode(encodeRules, str5);
		System.out.println("str6: " + str6);

		String key2 = "12365478998788";
		byte[] keyHeaderByte = new byte[] { (byte) 0xA5, (byte) 0x4B, (byte) 0x45, (byte) 0x59, (byte) 0xAA };
		String keyHeaderByteStr = Arrays.toString(keyHeaderByte);
		System.out.println("byte加密前: " + keyHeaderByteStr);

		byte[] keyHeaderByte2 = aesEncode(key2, keyHeaderByte);
		String keyHeaderByte2Str = Arrays.toString(keyHeaderByte2);
		System.out.println("byte加密后: " + keyHeaderByte2Str);

		byte[] keyHeaderByte3 = aesDecode(key2, keyHeaderByte2);
		String keyHeaderByte3Str = Arrays.toString(keyHeaderByte3);
		System.out.println("byte解密后: " + keyHeaderByte3Str);

	}

}